package com.aiss.ws.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.aiss.ws.Entity.CurseItem;
import com.aiss.ws.R;
import com.aiss.ws.activity.CourseListActivity_;
import com.aiss.ws.activity.InformationActivity_;
import com.aiss.ws.activity.LoginActivity_;
import com.aiss.ws.activity.RegistActivity_;
import com.aiss.ws.activity.TureDetailActivity_;
import com.aiss.ws.adapter.HomeAdatper;
import com.aiss.ws.httptools.LoadNetImageView;
import com.aiss.ws.utils.Command;
import com.aiss.ws.utils.Futil;
import com.aiss.ws.utils.SetViewHeight;
import com.aiss.ws.utils.Url;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by chenqiang on 16/5/8.
 */
@EFragment(R.layout.home_fragment)
public class HomeFragment extends BaseFragment {

    private List<CurseItem> datas;

    private int position;

    private Handler handler2 = new Handler(){
        public void handleMessage(android.os.Message msg) {
            poster.setCurrentItem(position);
        };
    };

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if(msg.what==Command.HANDLECODE23){
                try {
                    JSONObject obj = (JSONObject) msg.obj;
                    JSONObject jsonObject = obj.getJSONObject("return_data");

                    JSONArray array =  jsonObject.getJSONArray("banner");
                    for(int i = 0 ; i < array.length();i++){
                        urls.add(array.getJSONObject(i).getString("img"));
                    }


                    JSONArray jsonArray = jsonObject.getJSONArray("free_course");
                     datas = new ArrayList<>();
                    for(int i = 0 ; i < jsonArray.length();i++){
                        CurseItem item = new CurseItem();
                        String idx = jsonArray.getJSONObject(i).getString("idx");
                        String namex = jsonArray.getJSONObject(i).getString("namex");
                        item.setIdx(idx);
                        item.setNamex(namex);
                        datas.add(item);
                    }
                    HomeAdatper adatper = new HomeAdatper(datas,context);
                    listView.setAdapter(adatper);
                    SetViewHeight.setListViewHeightBasedOnChildren(listView);
                    adatper.notifyDataSetChanged();
                    home_fg.setVisibility(View.VISIBLE);
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            if(Futil.getValue(context, Command.SESSION_KEY,2)!=null&&!Futil.getValue(context,Command.SESSION_KEY,2).toString().equals("")){
                                TureDetailActivity_.intent(context).extra("item",datas.get(position)).extra("type",Command.SUITE[5]).extra("is_true",1).start();
                            }else{
                                RegistActivity_.intent(context).start();
                                showMessage("请登录",context);
                            }
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                setView();

            }

        }
    };

    @ViewById(R.id.home_fg)
    LinearLayout home_fg;


    private Context context;

    @ViewById(R.id.listView)
    ListView listView;

    private PagerAdapter pagerAdapter;

    private ArrayList<LoadNetImageView> imgs = new ArrayList<>();
    private ArrayList<String> urls = new ArrayList<>();
    private ArrayList<RadioButton> radioBtns = new ArrayList<>();

    @ViewById(R.id.poster)
    ViewPager poster;

    @ViewById(R.id.radio_container)
    RadioGroup radio_container;

    @AfterViews
    void init(){
        context = getActivity();
        pagerAdapter = new PagerAdapter() {
            @Override
            public void destroyItem(ViewGroup container, int position,
                                    Object object) {
                container.removeView(imgs.get(position));
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(imgs.get(position));
                return imgs.get(position);
            }

            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == arg1;
            }

            @Override
            public int getCount() {
                return imgs.size();
            }
        };
        poster.setAdapter(pagerAdapter);
        getText();
    }

    /**
     * 银行
     */
    @Click(R.id.ll1)
    void onClickll1(){
        CourseListActivity_.intent(this).extra("type",Command.COURSE[0]).start();
    }

    /**
     * 基金
     */
    @Click(R.id.ll2)
    void onClickll2(){
        CourseListActivity_.intent(this).extra("type",Command.COURSE[3]).start();
    }

    /**
     * 证劵
     */
    @Click(R.id.ll3)
    void onClickll3(){
        CourseListActivity_.intent(this).extra("type",Command.COURSE[1]).start();
    }

    /**
     * 期贷
     */
    @Click(R.id.ll4)
    void onClickll4(){
        CourseListActivity_.intent(this).extra("type",Command.COURSE[2]).start();
    }

    @UiThread
    void getText(){
        HashMap<String,String> hashMap = new HashMap<>();
        Futil.xutils(Url.BANNER,hashMap,handler, Command.HANDLECODE23);
    }

    public void setView(){
        LoadNetImageView  img1 = new LoadNetImageView(context);
        img1.setImageUrl(context, urls.get(urls.size()-1));
        imgs.add(img1);
        for(int i = 0; i< urls.size(); i++){
            final int index = i % urls.size();
            LoadNetImageView  img = new LoadNetImageView(context);
            img.setScaleType(ImageView.ScaleType.CENTER_CROP);
            img.setImageUrl(context, urls.get(i % urls.size()));
//            img.setOnClickListener(new View.OnClickListener() {
//
//                @Override
//                public void onClick(View v) {
//                    intent = new Intent(context,DetailActivity.class);
//                    intent.putExtra("title", xinwen_datas.get(index).get("title"));
//                    intent.putExtra("url", xinwen_datas.get(index).get("url"));
//                    intent.putExtra("id", 1);
//                    startActivity(intent);
//
//                }
//            });
            imgs.add(img);
        }
        LoadNetImageView  img = new LoadNetImageView(context);
        img.setScaleType(ImageView.ScaleType.CENTER_CROP);
        img.setImageUrl(context, urls.get(0));
        imgs.add(img);
        pagerAdapter.notifyDataSetChanged();
        poster.setCurrentItem(1);//从开始就可以向左滑
        poster.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {

                if (urls.size() > 1) { // 多于1，才会循环跳转
                    if (arg0 < 1) { // 首位之前，跳转到末尾（N）
                        arg0 = urls.size(); // 注意这里是mList，而不是mViews
                        poster.setCurrentItem(arg0, false);
                        ((RadioButton) radio_container.getChildAt(0))
                                .setChecked(true);
                    } else if (arg0 > urls.size()) { // 末位之后，跳转到首位（1）
                        poster.setCurrentItem(1, false); // false:不显示跳转过程的动画
                        arg0 = 1;
                        ((RadioButton) radio_container.getChildAt(urls.size()-1))
                                .setChecked(true);
                    }
                }
                position = arg0;
                if (radioBtns.size() > 1) {
                    for (int i = 0; i < radio_container.getChildCount(); i++) {
                        ((RadioButton) radio_container.getChildAt(0))
                                .setChecked(false);
                    }

                    ((RadioButton) radio_container.getChildAt((position-1 )% radioBtns.size()))
                            .setChecked(true);
                }


            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
        if(urls.size() > 1){
            for(int i = 0; i < urls.size(); i++){
                RadioButton r1 = new RadioButton(context);
                int margin = 30;
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                params.setMargins(margin, margin, margin, margin);
                r1.setButtonDrawable(R.drawable.radiobtn_bg);
                r1.setLayoutParams(params);
                r1.setClickable(false);
                if(i == 0)r1.setChecked(true);
                radioBtns.add(r1);
                radio_container.addView(r1);


            }
        }

        thread();
    }
    private Thread thread;
    private boolean flag = true;
    public void thread(){
        thread = new Thread(new Runnable() {

            @Override
            public void run() {
                while (flag) {
                    try {
                        Thread.sleep(3000);
                        handler2.sendEmptyMessage(position);
                        position++;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }



            }
        });
        thread.start();
    }

}
